package com.sjsm.sjsmscenerecord;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.sjsm.sjsmscenerecord.adapter.RecorderAdapter;
import com.sjsm.sjsmscenerecord.bean.Recorder;
import com.sjsm.sjsmscenerecord.constant.Constant;
import com.sjsm.sjsmscenerecord.utils.ImageHelper;
import com.sjsm.sjsmscenerecord.utils.MediaManager;
import com.sjsm.sjsmscenerecord.utils.ShowMsgUtils;
import com.sjsm.sjsmscenerecord.view.AudioRecordButton;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sjsm.sjsmscenerecord.constant.Constant.PHOTO_WITH_CAMERA;

/**
 * Created by hasee on 2017/8/21.
 */

public class ItemDetailActivity extends AppCompatActivity {
    @Bind(R.id.iv_add_preblem)
    ImageView ivAddPreblem;
    @Bind(R.id.lv_project_content)
    ListView lvProjectContent;
    @Bind(R.id.record_Button)
    AudioRecordButton recordButton;
    @Bind(R.id.ll_invisiable_photo)
    LinearLayout llInvisiablePhoto;
    @Bind(R.id.ll_invisiable_video)
    LinearLayout llInvisiableVideo;
    @Bind(R.id.ll_invisiable_reference)
    LinearLayout llInvisiableReference;
    @Bind(R.id.ll_invisiable_sticky)
    LinearLayout llInvisiableSticky;
    @Bind(R.id.ll_detail_invisiable_btn)
    LinearLayout llDetailInvisiableBtn;
    @Bind(R.id.iv_detail_keyboard)
    ImageView ivDetailKeyboard;
    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.btn_show_text)
    Button btnShowText;
    @Bind(R.id.iv_detail_more)
    ImageView ivDetailMore;
    private RecorderAdapter mAdapter;
    private List<Recorder> mDatas = new ArrayList<Recorder>();
    private View viewanim;

    //隐藏的按钮是否显示出来了,默认false
    private boolean isShow = false;

    //是否是文字输入,如果等0为文字,其他为语音,默认为语音
    private int isText = 1;
    //存储照片的路径
    private File Sjsm_Photo;
    //拍照的名称和类型
    private String FileName,FileType;
    //设置图片的position
    private int setPhoto = -1;


    private static final int CODE_GALLERY_REQUEST = 1;//选择相册图片
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_detail);
        ButterKnife.bind(this);
        //设置监听
        setListener();
    }

    private void setListener() {
        mAdapter = new RecorderAdapter(this, mDatas);
        lvProjectContent.setAdapter(mAdapter);
        lvProjectContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (mAdapter.getItemViewType(position)) {
                    case Constant.VOICE:
                        playVoice(view, position);
                        break;
                    case Constant.VIDEO:
                        playVideo(view, position);
                        break;
                    case Constant.PHOTO:
                        settingPhoto(view,position);
                        break;
                    case Constant.TEXT:
                        break;
                }


            }
        });
        recordButton.setAudioFinishRecorderListener(new AudioRecordButton.AudioFinishRecorderListener() {

            @Override
            public void onFinished(float seconds, String filePath) {
                // TODO Auto-generated method stub
                Toast.makeText(ItemDetailActivity.this, "录音~~~~~", Toast.LENGTH_SHORT).show();
                Recorder recorder = new Recorder(seconds, filePath, Constant.VOICE);
                mDatas.add(recorder);
                mAdapter.notifyDataSetChanged();
                lvProjectContent.setSelection(mDatas.size() - 1);
            }
        });
    }
    //设置图片
    private void settingPhoto(View view, int position) {
        setPhoto = position;
        Intent intent = new Intent(this,PhotoSettingActivity.class);
        intent.putExtra("photo_path",mDatas.get(position).getFilePathString());
        startActivityForResult(intent,Constant.PHOTO_SETTING);
    }

    /**
     * 播放小视频
     */
    private void playVideo(View view, int position) {
        Intent intent = new Intent(this, PlayVideoActivity.class);
        intent.putExtra("path", mDatas.get(position).getFilePathString());
        startActivity(intent);
    }

    /**
     * 播放录音
     */
    private void playVoice(View view, int position) {
        // TODO Auto-generated method stub
        // 播放动画
        if (viewanim != null) {//让第二个播放的时候第一个停止播放
            viewanim.setBackgroundResource(android.R.color.transparent);
            viewanim = null;
        }
        viewanim = view.findViewById(R.id.id_recorder_anim);
        viewanim.setBackgroundResource(R.drawable.play);
        AnimationDrawable drawable = (AnimationDrawable) viewanim
                .getBackground();
        drawable.start();
        Toast.makeText(ItemDetailActivity.this, "播音~~~~~", Toast.LENGTH_SHORT).show();
        // 播放音频
        MediaManager.playSound(mDatas.get(position).getFilePathString(),
                new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        viewanim.setBackgroundResource(R.drawable.adj);

                    }
                });
    }


    @OnClick({R.id.btn_show_text, R.id.iv_add_preblem, R.id.ll_invisiable_photo, R.id.ll_invisiable_video, R.id.ll_invisiable_reference, R.id.ll_invisiable_sticky,
            R.id.iv_detail_keyboard, R.id.iv_detail_more, R.id.iv_detail_photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add_preblem:
                // TODO: 2017/8/22 添加item的逻辑
                break;
            case R.id.ll_invisiable_photo:
                // TODO: 2017/8/22 选择照片

                break;
            case R.id.ll_invisiable_video:
                // TODO: 2017/8/22 小视频
                goActivity(MinVideoActivity.class);
                break;
            case R.id.ll_invisiable_reference:
                // TODO: 2017/8/22 标准引用
                break;
            case R.id.ll_invisiable_sticky:
                // TODO: 2017/8/22 问题便签
                break;
            case R.id.iv_detail_keyboard:
                // TODO: 2017/8/22 键盘语音切换
                isText = isText == 0 ? 1 : 0;
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                //此方法在显示键盘的时候隐藏,隐藏的时候可以调用英文输入软键盘,不建议使用
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                switch (isText) {
                    case 1: //语音
                        ivDetailKeyboard.setImageResource(R.drawable.keyboard);
                        etContent.setVisibility(View.GONE);
                        recordButton.setVisibility(View.VISIBLE);
                        btnShowText.setVisibility(View.GONE);
                        ivDetailMore.setVisibility(View.VISIBLE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        break;
                    case 0: //键盘
                        ivDetailKeyboard.setImageResource(R.drawable.ease_chatting_setmode_voice_btn_normal);
                        etContent.setVisibility(View.VISIBLE);
                        etContent.setFocusable(true);
                        etContent.setFocusableInTouchMode(true);
                        etContent.requestFocus();
                        recordButton.setVisibility(View.GONE);
                        btnShowText.setVisibility(View.VISIBLE);
                        ivDetailMore.setVisibility(View.GONE);
                        imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
                        break;
                }

                break;
            case R.id.iv_detail_more:
                // TODO: 2017/8/22 更多
                isShow = !isShow;
                llDetailInvisiableBtn.setVisibility(isShow ? View.VISIBLE : View.GONE);
                break;
            case R.id.iv_detail_photo:
                // TODO: 2017/8/22 拍照
                doTackPhoto();
                break;
            case R.id.btn_show_text:
                //文本发送
                break;
        }
    }

    private void doTackPhoto() {
        //如果内存卡正常挂载
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Sjsm_Photo = new File(Environment.getExternalStorageDirectory() + "/sjsm/sjsm_photo");
            if (!Sjsm_Photo.exists()) {
                Sjsm_Photo.mkdirs();
            }
        }
            FileName = ImageHelper.createPhotoFileName();
            FileType = ImageHelper.getFileType(FileName);
        //设置路径
            File imageFile = new File(Sjsm_Photo, FileName);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //如果版本小于android5.1
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            if (!Sjsm_Photo.exists()) {
                ShowMsgUtils.ShowMessage(this, "请打开允许存储权限！");
                return;
            }
        }else{
            //否则就是6.0以上的
            Uri imageUri = FileProvider.getUriForFile(this, "com.sjsm.sjsmscenerecord.fileprovider", imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        //如果不存在,说明木有权限
        if (!Sjsm_Photo.exists()) {
            ShowMsgUtils.ShowMessage(this, "请打开允许存储权限！");
            return;
        }
        //启动拍照等待结果
        startActivityForResult(intent, PHOTO_WITH_CAMERA);
    }

    private void goActivity(Class cls) {
        Intent intent = new Intent(this, cls);
        startActivityForResult(intent, Constant.MIN_VIDEO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //视频
            case Constant.MIN_VIDEO:
                if (data != null) {
                    String video_path = data.getStringExtra("path");
                    long video_time = data.getLongExtra("time", -1);
                    if (!video_path.isEmpty() && video_time != -1) {
                        File file = new File(video_path);
                        if (file.exists()) {
                            Recorder recorder = new Recorder(video_time, video_path, Constant.VIDEO);
                            mDatas.add(recorder);
                            mAdapter.notifyDataSetChanged();
                            lvProjectContent.setSelection(mDatas.size() - 1);
                        }
                    }
                }
                break;
            //拍照
            case Constant.PHOTO_WITH_CAMERA:
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        File imgFile = new File(Sjsm_Photo, FileName);
                        Recorder recorder = new Recorder(System.currentTimeMillis(), imgFile.getAbsolutePath(), Constant.PHOTO);
                        mDatas.add(recorder);
                        mAdapter.notifyDataSetChanged();
                        lvProjectContent.setSelection(mDatas.size() - 1);
                    } catch (Exception e) {
                        throw new  RuntimeException("文件获取出错!"+e.toString());
                    }
                }
                break;
            case Constant.PHOTO_SETTING:    //图片设置
                if (setPhoto!=-1&&null!=data){
                    boolean isSetting = data.getBooleanExtra("isSetting", false);
                    if (isSetting){
                        String newPath =data.getStringExtra("path");
                        if (newPath!=null){
                            mDatas.get(setPhoto).setFilePathString(newPath);
                            mAdapter.notifyDataSetChanged();
                            lvProjectContent.setSelection(setPhoto);
                            setPhoto = -1;
                        }

                    }

                }
        }
    }
}
